<template>
  <div class="call-terminal-container">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="280px" class="aside">
        <div class="logo-container">
          <img src="../../assets/logo.png" alt="Logo" class="logo">
          <h2>排队叫号系统</h2>
        </div>

        <!-- 窗口信息 -->
        <div class="window-info">
          <div class="window-number">{{ windowNumber }}号窗口</div>
          <div class="window-number">{{ serviceTypeName }}</div>
          <div class="staff-info">
            <img :src="staffAvatar || '../../assets/avatar.jpg'" alt="Staff" class="staff-avatar">
            <div class="staff-name">{{ staffName || '操作员' }}</div>
          </div>
        </div>

        <!-- 等待队列 -->
        <div class="waiting-list">
          <div class="waiting-header">
            <div class="waiting-title">排队列表</div>
            <div class="waiting-count">{{ waitingList.length || 0 }}人等待</div>
          </div>

          <el-scrollbar height="calc(100vh - 350px)">
            <div
              v-for="(ticket, index) in waitingList"
              :key="ticket.id"
              class="waiting-item"
              :class="{ 'waiting-item-first': index === 0 }"
            >
              <div class="ticket-number">{{ ticket.ticketNumber }}</div>
              <div class="ticket-info">
                <div class="business-type">{{ ticket.businessType }}</div>
                <div class="wait-time">已等待 {{ formatWaitTime(ticket.waitTime) }}</div>
              </div>
            </div>

            <el-empty
              v-if="waitingList.length === 0"
              description="暂无等待人员"
              :image-size="80"
            ></el-empty>
          </el-scrollbar>
        </div>

        <!-- 统计信息 -->
        <div class="statistics">
          <div class="statistics-item">
            <div class="statistics-value">{{ statistics.completedCount }}</div>
            <div class="statistics-label">今日已办理</div>
          </div>
          <div class="statistics-item">
            <div class="statistics-value">{{ formatTime(statistics.avgServiceTime) }}</div>
            <div class="statistics-label">平均办理时长</div>
          </div>
        </div>
      </el-aside>

      <!-- 主内容区 -->
      <el-container class="main-container">
        <el-header class="header">
          <div class="header-left">
            <div class="current-time">{{ currentTime }}</div>
          </div>
          <div class="header-right">
            <el-dropdown @command="handleCommand">
              <span class="user-menu">
                <img :src="staffAvatar || '../../assets/avatar.jpg'" alt="Staff" class="staff-avatar-small">
                <span>{{ staffName || '操作员' }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                  <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
                  <el-dropdown-item command="changeBusiness">切换业务</el-dropdown-item>
                  <el-dropdown-item command="refresh">刷新数据</el-dropdown-item>
                  <el-dropdown-item command="pause" v-if="windowStatus === 'OPEN'">暂停服务</el-dropdown-item>
                  <el-dropdown-item command="resume" v-else>恢复服务</el-dropdown-item>
                  <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <el-main class="main">
          <div class="service-area">
            <!-- 当前办理区域 -->
            <div class="current-ticket" v-if="currentTicket">
              <div class="ticket-header">
                <div class="ticket-title">当前办理</div>
                <div class="ticket-time">开始时间: {{ formatDateTime(currentTicket.startTime) }}</div>
              </div>

              <div class="ticket-content">
                <div class="ticket-big-number">{{ currentTicket.ticketNumber }}</div>
                <div class="ticket-details">
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="票号">{{ currentTicket.ticketNumber }}</el-descriptions-item>
                    <el-descriptions-item label="等待时间">{{ currentTicket.waitTime }}分钟</el-descriptions-item>
                    <el-descriptions-item label="业务类型">{{ currentTicket.businessType }}</el-descriptions-item>
                    <el-descriptions-item label="开始时间">{{ currentTicket.startTime }}</el-descriptions-item>
                    <el-descriptions-item label="验证状态" :class="getVerificationStatusClass">
                      {{ getVerificationStatusText }}
                    </el-descriptions-item>
                    <el-descriptions-item label="服务时长">
                      <span class="service-timer" :class="{ 'active': verificationStatus === 'SUCCESS' }">
                        {{ serviceTimeDisplay }}
                      </span>
                    </el-descriptions-item>
                  </el-descriptions>
                  </div>
                  </div>

              <div class="action-buttons">
                <div class="button-group">
                  <el-button
                    type="primary"
                    size="default"
                    icon="Bell"
                    @click="replayCurrentCall"
                    :disabled="!currentTicket"
                    class="action-button"
                  >
                    重播叫号
                  </el-button>
                  </div>

                <div class="button-group">
                  <el-button
                    type="success"
                    size="default"
                    icon="Check"
                    @click="handleComplete"
                    :disabled="isCompleteDisabled"
                    class="action-button"
                  >
                    完成办理
                  </el-button>

                  <el-button
                    type="warning"
                    size="default"
                    icon="Close"
                    @click="handleNoShow"
                    :disabled="isNoShowDisabled"
                    class="action-button"
                  >
                    {{ verificationStatus === 'SUCCESS' ? '客户已到' : '客户未到' }}
                  </el-button>
                  </div>
              </div>
            </div>

            <!-- 无办理信息 -->
            <div class="no-ticket" v-else>
              <el-empty description="暂无办理信息" :image-size="120">
                <template #description>
                  <p>暂无客户办理业务</p>
                </template>
                <el-button
                  type="primary"
                  size="default"
                  icon="Right"
                  @click="handleCallNext"
                  :disabled="waitingList.length === 0 || windowStatus !== 'OPEN'"
                  class="no-ticket-button"
                >
                  {{ waitingList.length > 0 ? '呼叫下一位' : '暂无等待客户' }}
                </el-button>
              </el-empty>
            </div>
          </div>

          <!-- 历史记录 -->
          <div class="history-area">
            <div class="history-header">
              <div class="history-title">今日办理历史</div>
            </div>

            <el-table
              :data="historyList"
              style="width: 100%"
              :max-height="400"
              stripe
              v-loading="historyLoading"
            >
              <el-table-column prop="ticketNumber" label="票号" width="80" />
              <el-table-column prop="businessType" label="业务类型" width="120" />
              <el-table-column label="等待时间" width="100">
                <template #default="scope">
                  {{ formatWaitTime(scope.row.waitTime) }}
                </template>
              </el-table-column>
              <el-table-column label="办理时间" width="100">
                <template #default="scope">
                  {{ formatTime(scope.row.serviceTime) }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="完成时间" min-width="150">
                <template #default="scope">
                  {{ formatDateTime(scope.row.endTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 语音播放器 -->
    <audio ref="callVoice" preload="auto"></audio>

    <!-- 个人信息对话框 -->
    <el-dialog
      v-model="profileDialog.visible"
      title="个人信息"
      width="500px"
    >
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">点击上传头像 (JPG/PNG)</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="profileDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog
        title="请选择业务类型"
        v-model="businessShow.visible"
        width="500px"
    >
      <el-select v-model="selectedType" placeholder="请选择业务类型" style="width: 100%">
        <el-option
            v-for="item in businessTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
      <template #footer>
        <el-button @click="businessShow.visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialog.visible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="savePassword">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Plus } from '@element-plus/icons-vue'
import axios from "axios";
import {formatStandardTime, getMinutesDifference} from "@/utils/date";
window.addEventListener('beforeunload', function (event) {
  // 自定义提示信息（部分浏览器会忽略自定义消息）
  event.preventDefault();
  event.returnValue = ''; // 某些浏览器需要设置 returnValue
  socket.close();
});
let sessionId = null;
// 创建 WebSocket 连接
const socket = new WebSocket('ws://127.0.0.1:8080/api/ws/queue-status');
// 监听连接成功事件
socket.addEventListener('open', function (event) {
  console.log('WebSocket 连接已建立');
});

// 监听接收消息事件
socket.addEventListener('message', function (event) {
  console.log('收到消息:', event.data);
  // 如果需要解析 JSON 数据
  try {
    const data = JSON.parse(event.data);
    if (data.type === 'connect') {
      sessionId = data.data;
      console.log('sessionId:', sessionId);
    } else if (data.type === 'reFreshData') {
      getHistoryList();
      getWaitingList();
    }
  } catch (error) {
    console.error('消息解析失败:', error);
  }
});


// 监听错误事件
socket.addEventListener('error', function (event) {
  console.error('WebSocket 错误:', event);
});

// 监听连接关闭事件
socket.addEventListener('close', function (event) {
  console.log('WebSocket 连接已关闭:', event);
});


// 路由实例
    const router = useRouter()

    // 当前时间
    const currentTime = ref('')

// 窗口信息 - 模拟数据
const windowId = ref(1)
const windowNumber = ref(1)

const serviceTypeId = ref(null);
const serviceTypeName = ref('');
const selectedType = ref(null);

const businessShow = reactive({
  visible: false
});

const windowStatus = ref('OPEN') // OPEN, PAUSE
const staffName = ref('张三')
const staffAvatar = ref('../../assets/avatar.jpg')

const businessTypes = ref([]);
let businessTypeMap = new Map;
axios.get("/service-types/getList", {
  params: {
    "pageNum": 1,
    "pageSize": 100,
    "status": 1,
  }
}).then(res => {
  res.data.data.list.forEach(item => {
    businessTypes.value.push(item);
    businessTypeMap.set(item.id, item);
  })
  serviceTypeName.value = businessTypes.value[0].name;
  serviceTypeId.value = businessTypes.value[0].id;
});
const handleConfirm = () => {
  serviceTypeName.value = businessTypeMap.get(selectedType.value).name;
  serviceTypeId.value = selectedType.value;
  businessShow.visible = false;
}

// 当前办理的票 - 初始为空
const currentTicket = ref(null)
axios.get("/callTerminal/getCurrentQueueByWindow", {
  params: {
    "windowId": windowId.value,
  }
}).then(res => {
  const nextCustomer = res.data.data;
  if (!nextCustomer) {
    return;
  }
  nextCustomer.businessType = nextCustomer.serviceTypeName;
  nextCustomer.waitTime = getMinutesDifference(nextCustomer.createTime)
  // 设置为当前办理客户
  const now = new Date()
  currentTicket.value = {
    ...nextCustomer,
    startTime: formatDateTime(now)
  }

  // 初始化验证状态
  verificationStatus.value = 'NONE'

  // 重置服务时间
  serviceTime.value = 0
  serviceTimeDisplay.value = '00:00:00'

  // 停止可能存在的服务计时器
  if (serviceTimeInterval.value) {
    clearInterval(serviceTimeInterval.value)
    serviceTimeInterval.value = null
  }

  // 播放叫号语音
  playCallVoice()

  // 发送票号到人脸验证页面
  openOrReuseVerifyWindow(currentTicket.value.ticketNumber)
});

// 等待队列 - 模拟数据
const waitingList = ref([

])
getWaitingList();
function getWaitingList() {
  axios.get("/callTerminal/getWaitingQueuesByServiceType").then(res => {
    waitingList.value = [];
    res.data.data.forEach(item => {
      let data = {
        id: item.id,
        ticketNumber: item.ticketNumber,
        businessType: item.serviceTypeName,
        waitTime: getMinutesDifference(item.createTime),
        createTime: item.createTime
      }
      waitingList.value.push(data);
    })
  });
}


// 历史记录
const historyList = ref([

])
getHistoryList();
function getHistoryList() {
  axios.get("/callTerminal/getQueueHistoryByWindowId", {
    params: {
      windowId: windowId.value,
    }
  }).then(res => {
    historyList.value = [];
    statistics.completedCount = 0;
    statistics.noShowCount = 0;
    statistics.avgServiceTime = 0;
    let totolTime = 0;
    res.data.data.forEach(item => {
      item.businessType = item.serviceTypeName;
      item.serviceTime = getMinutesDifference(item.callTime, item.endTime);
      item.endTime = formatStandardTime(item.endTime)
      item.waitTime = getMinutesDifference(item.createTime, item.callTime);
      historyList.value.push(item);
      if (item.status === 'COMPLETED') {
        statistics.completedCount++
        totolTime += item.serviceTime;
      } else if (item.status === 'NO_SHOW') {
        statistics.noShowCount++
      }
    })
    statistics.avgServiceTime = Math.floor(totolTime /  statistics.completedCount);
  });
}

    // 统计信息
const statistics = reactive({
  completedCount: 0,
  noShowCount: 0,
  avgServiceTime: 0
})

// 加载状态
const historyLoading = ref(false)

    // 语音播放器
    const callVoice = ref(null)

// 添加个人信息表单数据
const profileDialog = reactive({
  visible: false
})

const profileFormRef = ref(null)
const profileForm = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  avatar: ''
})

const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 添加修改密码表单数据
const passwordDialog = reactive({
  visible: false
})

const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

    // 更新当前时间
    const updateTime = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const date = now.getDate().toString().padStart(2, '0')
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      const seconds = now.getSeconds().toString().padStart(2, '0')
      const day = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()]

      currentTime.value = `${year}年${month}月${date}日 ${hours}:${minutes}:${seconds} ${day}`
    }

    // 格式化等待时间
const formatWaitTime = (minutes) => {
  if (!minutes) return '刚刚到达'

      if (minutes < 60) {
        return `${minutes}分钟`
      } else {
        const hours = Math.floor(minutes / 60)
        const mins = minutes % 60
    return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`
  }
}

// 格式化办理时间
const formatTime = (minutes) => {
  if (!minutes && minutes !== 0) return '-'
        return `${minutes}分钟`
    }

    // 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '-'

  // 如果是Date对象，转换为字符串格式
  if (datetime instanceof Date) {
    const year = datetime.getFullYear()
    const month = (datetime.getMonth() + 1).toString().padStart(2, '0')
    const date = datetime.getDate().toString().padStart(2, '0')
    const hours = datetime.getHours().toString().padStart(2, '0')
    const minutes = datetime.getMinutes().toString().padStart(2, '0')
    const seconds = datetime.getSeconds().toString().padStart(2, '0')

    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
  }

  return datetime
    }

    // 格式化手机号
    const formatPhone = (phone) => {
  if (!phone) return '-'
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }

    // 获取状态类型
    const getStatusType = (status) => {
  const statusMap = {
    'WAITING': '',
    'SERVING': 'warning',
    'COMPLETED': 'success',
    'NO_SHOW': 'danger'
  }
  return statusMap[status] || ''
    }

    // 获取状态文本
    const getStatusText = (status) => {
  const statusMap = {
    'WAITING': '等待中',
    'SERVING': '办理中',
    'COMPLETED': '已完成',
    'NO_SHOW': '未到场'
  }
  return statusMap[status] || '未知'
}

// 人脸验证状态的样式
const getVerificationStatusClass = computed(() => {
  const statusClassMap = {
    'NONE': 'status-none',
    'WAITING': 'status-waiting',
    'SUCCESS': 'status-success',
    'FAILED': 'status-failed'
  }
  return statusClassMap[verificationStatus.value] || ''
})

// 人脸验证状态的文本
const getVerificationStatusText = computed(() => {
  const statusTextMap = {
    'NONE': '等待验证',
    'WAITING': '验证中...',
    'SUCCESS': '验证成功',
    'FAILED': '验证失败'
  }
  return statusTextMap[verificationStatus.value] || '未验证'
})

// 人脸验证状态
const verificationStatus = ref('NONE') // NONE, WAITING, SUCCESS, FAILED

// 人脸验证页面URL和窗口引用
const faceVerifyPageUrl = '/faceVerify'
let faceVerifyWindow = null
let verifyWindowCheckTimer = null

// 初始化人脸验证页面
const initFaceVerifyPage = () => {
  // 如果验证页面窗口已经存在且未关闭，不需要再次创建
  if (faceVerifyWindow && !faceVerifyWindow.closed) {
    console.log('人脸验证页面已存在')
    return
  }

  // 创建新的人脸验证页面窗口
  console.log('创建新的人脸验证页面')
  // faceVerifyWindow = window.open(faceVerifyPageUrl, 'FaceVerifyWindow', 'width=600,height=800')

  // if (!faceVerifyWindow) {
  //   ElMessage.error('无法打开人脸验证窗口，请检查浏览器是否阻止了弹出窗口')
  //   return false
  // }

  // 启动定时检查验证窗口是否关闭
  startVerifyWindowCheck()
  return true
}

// 向人脸验证页面发送票号
const sendTicketToVerifyPage = (ticketNumber) => {
  // 确保验证页面已经初始化
  if (!faceVerifyWindow || faceVerifyWindow.closed) {
    const success = initFaceVerifyPage()
    if (!success) return false

    // 新窗口刚刚创建，可能需要等待其加载完成
    setTimeout(() => {
      sendTicketDataToWindow(ticketNumber)
    }, 1000)
  } else {
    // 窗口已存在，直接发送票号
    sendTicketDataToWindow(ticketNumber)
  }

  return true
}

// 发送票号数据到验证窗口
const sendTicketDataToWindow = (ticketNumber) => {
  try {
    // 发送消息给验证页面
    faceVerifyWindow.postMessage({
      type: 'SET_TICKET_NUMBER',
      ticketNumber: ticketNumber,
      windowNumber: windowNumber.value,
      timestamp: new Date().toISOString()
    }, '*')

    // 聚焦窗口
    faceVerifyWindow.focus()

    console.log(`已向验证页面发送票号: ${ticketNumber}`)
    return true
  } catch (error) {
    console.error('向验证窗口发送消息失败:', error)
    ElMessage.error('与验证页面通信失败，请刷新页面重试')
    return false
  }
}

// 启动验证窗口检查
const startVerifyWindowCheck = () => {
  // 每5秒检查一次验证窗口是否关闭
  if (verifyWindowCheckTimer) {
    clearInterval(verifyWindowCheckTimer)
  }

  verifyWindowCheckTimer = setInterval(() => {
    if (faceVerifyWindow && faceVerifyWindow.closed) {
      console.log('检测到人脸验证窗口已关闭')
      stopVerifyWindowCheck()
      faceVerifyWindow = null

      // 如果窗口被关闭且当前有客户正在验证，设置为验证失败
      if (currentTicket.value && (verificationStatus.value === 'NONE' || verificationStatus.value === 'WAITING')) {
        verificationStatus.value = 'FAILED'
        ElMessage.warning('人脸验证窗口已关闭，验证未完成')
      }
    }
  }, 5000)
}

// 停止验证窗口检查
const stopVerifyWindowCheck = () => {
  if (verifyWindowCheckTimer) {
    clearInterval(verifyWindowCheckTimer)
    verifyWindowCheckTimer = null
  }
}

// 服务时间相关变量和函数
const serviceTime = ref(0)
const serviceTimeInterval = ref(null)
const serviceTimeDisplay = ref('00:00:00')

// 格式化服务时间
const formatServiceTime = (seconds) => {
  const hours = Math.floor(seconds / 3600).toString().padStart(2, '0')
  const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0')
  const secs = (seconds % 60).toString().padStart(2, '0')
  return `${hours}:${minutes}:${secs}`
}

// 开始服务计时
const startServiceTimer = () => {
  // 重置服务时间
  serviceTime.value = 0

  // 清除可能存在的旧计时器
  if (serviceTimeInterval.value) {
    clearInterval(serviceTimeInterval.value)
  }

  // 启动新的计时器
  serviceTimeInterval.value = setInterval(() => {
    serviceTime.value++
    // 更新显示
    serviceTimeDisplay.value = formatServiceTime(serviceTime.value)
  }, 1000)
}

// 停止服务计时
const stopServiceTimer = () => {
  if (serviceTimeInterval.value) {
    clearInterval(serviceTimeInterval.value)
    serviceTimeInterval.value = null

    // 返回当前的服务时间
    return serviceTime.value
  }
  return 0
}

// 语音播报功能
const speakText = (text) => {
  // 检查浏览器是否支持语音合成
  if ('speechSynthesis' in window) {
    // 停止任何正在进行的语音
    window.speechSynthesis.cancel()

    // 创建语音对象
    const utterance = new SpeechSynthesisUtterance(text)

    // 设置语音属性
    utterance.lang = 'zh-CN' // 设置中文
    utterance.rate = 1.0 // 语速
    utterance.pitch = 1.0 // 音调
    utterance.volume = 1.0 // 音量

    // 开始播放语音
    window.speechSynthesis.speak(utterance)

    return true
      } else {
    console.error('当前浏览器不支持语音合成功能')
    return false
  }
}

// 重播相关变量
const callRepeatCount = ref(0)
const callRepeatTimer = ref(null)

// 叫号语音播报
const playCallVoice = (isManualRepeat = false) => {
  if (!currentTicket.value) return

  // 如果是手动重播，重置计数
  if (isManualRepeat) {
    callRepeatCount.value = 0
    // 清除可能存在的自动重播定时器
    if (callRepeatTimer.value) {
      clearTimeout(callRepeatTimer.value)
      callRepeatTimer.value = null
    }
  }

  const ticketNumber = currentTicket.value.ticketNumber

  // 构建播报文本
  const text = `${ticketNumber}号请到${windowNumber.value}号窗口办理业务`

  // 播放叫号语音
  const speechSuccess = speakText(text)

  // 如果语音合成失败或不支持，尝试使用音频文件
  if (!speechSuccess && callVoice.value) {
    try {
      // 在实际应用中，这里可以播放预设的叫号声音
      callVoice.value.play()
    } catch (error) {
      console.error('播放语音文件失败:', error)
    }
  }

  // 增加播报计数
  callRepeatCount.value++

  // 如果未达到最大重复次数，设置定时器进行重复播报
  if (callRepeatCount.value <= 1) {
    callRepeatTimer.value = setTimeout(() => {
      playCallVoice()
    }, 8000) // 8秒后重复播报
          } else {
    callRepeatCount.value = 0
  }
}


// 添加取号成功后通知大屏幕显示排队信息
const sendQueueToScreen = (ticketData) => {
  const queueChannel = new BroadcastChannel('queue_screen_channel')

  queueChannel.postMessage({
    ticketNumber: ticketData.ticketNumber,
    businessType: ticketData.businessType,
    waitTime: ticketData.waitTime || 0,
    timestamp: Date.now()
  })

  console.log('已通知大屏添加排队信息:', ticketData.ticketNumber)
}

// 处理客户完成服务
const handleComplete = () => {
  if (!currentTicket.value) {
    ElMessage.warning('没有正在办理的业务')
    return
  }

  ElMessageBox.confirm('确认已完成当前客户的服务?', '完成服务', {
    confirmButtonText: '确认完成',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    const completedTicket = {
      ...currentTicket.value
    }
    console.log(completedTicket)
    axios.post("/callTerminal/completeService", {
      windowId: windowId.value,
      ticketNumber: currentTicket.value.ticketNumber
    }).then(() => {
      ElMessage.success('已完成当前客户的服务')
      reset("PENDING");
    });
    // 显示成功消息

  }).catch(() => {
    // 用户取消
  })
}


// 处理客户未到场
const handleNoShow = () => {
  if (!currentTicket.value) {
    ElMessage.warning('没有正在办理的业务')
    return
  }

  ElMessageBox.confirm('确认客户未到场?', '未到场', {
    confirmButtonText: '确认未到',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const noShowTicket = {
      ...currentTicket.value
    }
    axios.get('/callTerminal/markAsNoShow', {
      params: {
        ticketNumber: noShowTicket.ticketNumber,
        windowId: windowId.value,
      }
    }).then(() => {
      ElMessage.warning('已标记客户未到场')
      reset("PENDING");
    });
    // 显示信息
  }).catch(() => {
    // 用户取消
  })
}

function reset(status) {
  getWaitingList();
  // 添加到历史记录
  getHistoryList()
  // 重置当前票号和验证状态
  currentTicket.value = null
  verificationStatus.value = status

  // 停止服务计时
  clearInterval(serviceTimeInterval.value)
  serviceTime.value = 0

  // 停止验证窗口监控
  stopVerifyWindowCheck()
}

// 处理菜单命令
    const handleCommand = (command) => {
      switch (command) {
    case 'profile':
      profileDialog.visible = true
      break
    case 'changePassword':
      passwordDialog.visible = true
      break
        case 'refresh':
      ElMessage.success('数据已刷新')
          break
        case 'pause':
      windowStatus.value = 'PAUSE'
      ElMessage.warning('窗口已暂停服务')
          break
        case 'resume':
      windowStatus.value = 'OPEN'
      ElMessage.success('窗口已恢复服务')
          break
        case 'logout': {
          handleLogout()
          break
        }
        case "changeBusiness" : {
          businessShow.visible = true;
          break;
        }
      }
    }

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除登录信息
    localStorage.removeItem('token')
    localStorage.removeItem('tokenHead')
    localStorage.removeItem('expireTime')
    localStorage.removeItem('userInfo')

    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {
    // 取消退出
  })
}

// 定时更新等待时间
const updateWaitTime = () => {
  // 更新等待队列的等待时间
  waitingList.value.forEach(ticket => {
    ticket.waitTime++
  })
}

// 定时器
let timer = null
let waitTimeTimer = null

// 获取用户信息
const loadUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      staffName.value = userInfo.name || userInfo.username

      // 加载当前用户的注册信息（如果是注册用户）
      if (userInfo.id > 3) { // id > 3 表示是注册用户
        const registeredUsers = getRegisteredUsers()
        const currentUser = registeredUsers.find(user => user.id === userInfo.id)
        if (currentUser) {
          staffName.value = currentUser.name
          staffAvatar.value = currentUser.avatar || '../../assets/avatar.jpg'

          // 填充个人信息表单
          profileForm.username = currentUser.username
          profileForm.name = currentUser.name
          profileForm.phone = currentUser.phone
          profileForm.email = currentUser.email
          profileForm.avatar = currentUser.avatar
        }
      }
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
}

// 获取已注册用户列表
const getRegisteredUsers = () => {
  const usersStr = localStorage.getItem('registeredUsers')
  return usersStr ? JSON.parse(usersStr) : []
}

// 保存用户列表到localStorage
const saveRegisteredUsers = (users) => {
  localStorage.setItem('registeredUsers', JSON.stringify(users))
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 模拟头像上传
const handleAvatarUpload = (options) => {
  const file = options.file
  // 使用 FileReader 进行 base64 编码
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    profileForm.avatar = reader.result
    ElMessage.success('头像上传成功')
  }
}

// 保存个人信息
const saveProfile = () => {
  profileFormRef.value.validate((valid) => {
    if (valid) {
      // 获取当前用户信息
      const userInfoStr = localStorage.getItem('userInfo')
      if (!userInfoStr) {
        ElMessage.error('未找到用户信息')
        return
      }

      const userInfo = JSON.parse(userInfoStr)

      // 更新注册用户信息（如果是注册用户）
      if (userInfo.id > 3) {
        const registeredUsers = getRegisteredUsers()
        const index = registeredUsers.findIndex(user => user.id === userInfo.id)

        if (index > -1) {
          registeredUsers[index] = {
            ...registeredUsers[index],
            name: profileForm.name,
            phone: profileForm.phone,
            email: profileForm.email,
            avatar: profileForm.avatar
          }

          saveRegisteredUsers(registeredUsers)

          // 更新当前显示的用户名和头像
          staffName.value = profileForm.name
          staffAvatar.value = profileForm.avatar

          // 更新userInfo中的name
          const updatedUserInfo = {
            ...userInfo,
            name: profileForm.name
          }
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))

          ElMessage.success('个人信息更新成功')
          profileDialog.visible = false
        }
          } else {
        ElMessage.warning('系统内置用户不支持修改信息')
      }
    }
  })
}

// 保存新密码
const savePassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      // 获取当前用户信息
      const userInfoStr = localStorage.getItem('userInfo')
      if (!userInfoStr) {
        ElMessage.error('未找到用户信息')
        return
      }

      const userInfo = JSON.parse(userInfoStr)

      // 更新注册用户密码（如果是注册用户）
      if (userInfo.id > 3) {
        const registeredUsers = getRegisteredUsers()
        const userIndex = registeredUsers.findIndex(user => user.id === userInfo.id)

        if (userIndex > -1) {
          // 验证原密码
          if (registeredUsers[userIndex].password !== passwordForm.oldPassword) {
            ElMessage.error('原密码不正确')
            return
          }

          // 更新密码
          registeredUsers[userIndex].password = passwordForm.newPassword
          saveRegisteredUsers(registeredUsers)

          ElMessage.success('密码修改成功')
          passwordDialog.visible = false

          // 清空表单
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
        }
      } else {
        ElMessage.warning('系统内置用户不支持修改密码')
      }
    }
  })
}

// 处理呼叫下一位
const handleCallNext = () => {
  if (waitingList.value.length === 0) {
    ElMessage.warning('暂无等待客户')
    return
  }
  // 如果当前有客户正在办理，先确认是否结束当前业务
  if (currentTicket.value) {
    // 弹窗确认是否结束当前业务
    ElMessageBox.confirm('当前还有客户正在办理，是否结束当前业务并叫号下一位?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      // 呼叫下一位
      apiCallNex(true);
    }).catch(() => {
      // 用户取消操作
    })
  } else {
    // 没有正在办理的客户，直接叫号下一位
    apiCallNex(false);
  }
}

function apiCallNex(forceTransfer) {
  axios.post("/callTerminal/callNextCustomer", {
    "windowId": windowId.value,
    "forceTransfer": forceTransfer,
    "serviceTypeId": serviceTypeId.value
  }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.error(res.data.message)
      return
    }
    const nextCustomer = res.data.data;
    nextCustomer.businessType = nextCustomer.serviceTypeName;
    nextCustomer.waitTime = getMinutesDifference(nextCustomer.createTime)
    // 设置为当前办理客户
    const now = new Date()
    currentTicket.value = {
      ...nextCustomer,
      startTime: formatDateTime(now)
    }

    // 初始化验证状态
    verificationStatus.value = 'NONE'

    // 重置服务时间
    serviceTime.value = 0
    serviceTimeDisplay.value = '00:00:00'

    // 停止可能存在的服务计时器
    if (serviceTimeInterval.value) {
      clearInterval(serviceTimeInterval.value)
      serviceTimeInterval.value = null
    }

    // 播放叫号语音
    playCallVoice()

    // 发送票号到人脸验证页面
    openOrReuseVerifyWindow(currentTicket.value.ticketNumber)

    ElMessage.success(`已呼叫 ${nextCustomer.ticketNumber} 号客户进行业务办理`)
  });
}

// 打开或复用人脸验证窗口
const openOrReuseVerifyWindow = (ticketNumber) => {
  const url = `/faceVerify?ticketNumber=${ticketNumber}&windowId=${windowId.value}`
  // 如果窗口已经存在且未关闭，发送票号
  if (faceVerifyWindow && !faceVerifyWindow.closed) {
    // 尝试向已有窗口发送消息
    try {
      faceVerifyWindow.postMessage({
        type: 'SET_TICKET_NUMBER',
        ticketNumber: ticketNumber,
        windowNumber: windowNumber.value,
        timestamp: new Date().toISOString()
      }, '*')

      // 聚焦窗口
      faceVerifyWindow.focus()

      console.log(`向验证窗口发送票号: ${ticketNumber}`)

      // 启动验证窗口检查
      startVerifyWindowCheck()

      return true
    } catch (error) {
      console.error('向验证窗口发送消息失败:', error)
      // 如果发送失败，尝试创建新窗口
    }
  }

  // 创建新窗口
  faceVerifyWindow = window.open(url, `VerifyWindow_${windowNumber.value}`, 'width=600,height=800')

  if (!faceVerifyWindow) {
    ElMessage.error('无法打开人脸验证窗口，请检查浏览器是否阻止了弹出窗口')
    return false
  }

  // 启动验证窗口检查
  startVerifyWindowCheck()

  return true
}

// 监听人脸验证结果
window.addEventListener('message', (event) => {
  try {
    // 验证消息来源（在生产环境中应该进行更严格的验证）
    console.log('监听人脸验证结果-收到消息:', event.data)

    // 处理验证开始消息
    if (event.data.type === 'FACE_VERIFICATION_STARTED') {
      // 确保是当前票号的验证
      if (currentTicket.value && event.data.ticketNumber === currentTicket.value.ticketNumber) {
        verificationStatus.value = 'WAITING'
        console.log('客户开始验证:', event.data.ticketNumber)
      }
    }

    // 处理验证结果消息
    if (event.data.type === 'FACE_VERIFICATION_RESULT') {
      // 确保是当前票号的验证结果
      if (currentTicket.value && event.data.ticketNumber === currentTicket.value.ticketNumber) {
        // 更新验证状态
        verificationStatus.value = event.data.success ? 'SUCCESS' : 'FAILED'

        if (event.data.success) {
          // 验证成功，开始服务计时
          startServiceTimer()

          ElMessage.success(`票号 ${event.data.ticketNumber} 验证成功，开始服务`)
        } else {
          ElMessage.error(`票号 ${event.data.ticketNumber} 验证失败`)
        }
      }
    }
  } catch (error) {
    console.error('处理验证消息出错:', error)
  }
})

// 添加备选的验证结果监听方式
const checkFaceVerifyResult = () => {
  try {
    // 通过BroadcastChannel监听验证结果
    const verifyChannel = new BroadcastChannel('face_verify_channel')

    verifyChannel.onmessage = (event) => {
      try {
        if (event.data && event.data.type === 'FACE_VERIFICATION_RESULT') {
          const data = event.data

          // 处理验证结果，与window.message事件处理逻辑相同
          if (currentTicket.value && data.ticketNumber === currentTicket.value.ticketNumber) {
            // 更新验证状态
            verificationStatus.value = data.success ? 'SUCCESS' : 'FAILED'

            if (data.success) {
              // 验证成功，开始服务计时
              startServiceTimer()

              ElMessage.success(`票号 ${data.ticketNumber} 验证成功，开始服务`)
            } else {
              ElMessage.error(`票号 ${data.ticketNumber} 验证失败`)
            }
          }
        }
      } catch (error) {
        console.error('处理BroadcastChannel验证消息出错:', error)
      }
    }

    // 定期检查localStorage中的验证结果
    const localStorageCheckTimer = setInterval(() => {
      try {
        const verifyResultStr = localStorage.getItem('face_verify_result')
        if (verifyResultStr) {
          const verifyResult = JSON.parse(verifyResultStr)

          // 检查时间戳，只处理最近30秒内的数据
          if (verifyResult && Date.now() - verifyResult.timestamp < 30 * 1000) {
            console.log('从localStorage读取到验证结果:', verifyResult)

            // 处理验证结果，与window.message事件处理逻辑相同
            if (currentTicket.value && verifyResult.ticketNumber === currentTicket.value.ticketNumber) {
              // 更新验证状态
              verificationStatus.value = verifyResult.success ? 'SUCCESS' : 'FAILED'

              if (verifyResult.success) {
                // 验证成功，开始服务计时
                startServiceTimer()

                ElMessage.success(`票号 ${verifyResult.ticketNumber} 验证成功，开始服务`)
              } else {
                ElMessage.error(`票号 ${verifyResult.ticketNumber} 验证失败`)
              }

              // 处理完后清除，避免重复处理
              localStorage.removeItem('face_verify_result')
            }
          }
        }
      } catch (error) {
        console.error('检查localStorage验证结果出错:', error)
      }
    }, 2000) // 每2秒检查一次

    // 返回清理函数
    return () => {
      verifyChannel.close()
      clearInterval(localStorageCheckTimer)
    }
  } catch (error) {
    console.error('初始化验证结果监听失败:', error)

    // 如果BroadcastChannel不可用，只使用localStorage检查
    const localStorageCheckTimer = setInterval(() => {
      try {
        const verifyResultStr = localStorage.getItem('face_verify_result')
        if (verifyResultStr) {
          const verifyResult = JSON.parse(verifyResultStr)

          // 检查时间戳，只处理最近30秒内的数据
          if (verifyResult && Date.now() - verifyResult.timestamp < 30 * 1000) {
            console.log('从localStorage读取到验证结果:', verifyResult)

            // 处理验证结果
            if (currentTicket.value && verifyResult.ticketNumber === currentTicket.value.ticketNumber) {
              // 更新验证状态
              verificationStatus.value = verifyResult.success ? 'SUCCESS' : 'FAILED'

              if (verifyResult.success) {
                // 验证成功，开始服务计时
                startServiceTimer()

                ElMessage.success(`票号 ${verifyResult.ticketNumber} 验证成功，开始服务`)
              } else {
                ElMessage.error(`票号 ${verifyResult.ticketNumber} 验证失败`)
              }

              // 处理完后清除，避免重复处理
              localStorage.removeItem('face_verify_result')
            }
          }
        }
      } catch (error) {
        console.error('检查localStorage验证结果出错:', error)
      }
    }, 2000) // 每2秒检查一次

    // 返回清理函数
    return () => {
      clearInterval(localStorageCheckTimer)
    }
  }
}

// 手动重播当前叫号
const replayCurrentCall = () => {
  if (!currentTicket.value) {
    ElMessage.warning('当前没有正在办理的客户');
    return;
  }

  ElMessage.success('正在重新播报当前叫号');
  playCallVoice(true);
}

// 通过计算属性控制按钮状态
const isCallNextDisabled = computed(() => {
  // 没有等待的客户或窗口暂停时禁用
  if (waitingList.value.length === 0 || windowStatus.value !== 'OPEN') {
    return true
  }

  // 如果当前有票号，且验证状态不是成功，禁用呼叫下一位按钮
  if (currentTicket.value && verificationStatus.value !== 'SUCCESS') {
    return true
  }

  // 其他情况允许呼叫下一位
  return false
})

// 完成办理按钮禁用状态
const isCompleteDisabled = computed(() => {
  // 如果没有当前票号，禁用完成办理按钮
  if (!currentTicket.value) {
    return true
  }

  // 如果验证状态是NONE或WAITING（尚未完成验证），禁用完成办理按钮
  if (verificationStatus.value === 'NONE' || verificationStatus.value === 'WAITING') {
    return true
  }
  // 其他情况（验证成功或失败）允许完成办理
  return false
})

// 客户未到按钮禁用状态
const isNoShowDisabled = computed(() => {
  // 如果没有当前票号，禁用客户未到按钮
  if (!currentTicket.value) {
    return true
  }

  // 如果验证状态是成功，禁用客户未到按钮（客户已到，不能标记为未到）
  if (verificationStatus.value === 'SUCCESS') {
    return true
  }

  // 其他情况允许标记为客户未到
  return false
})

    onMounted(() => {
  // 更新当前时间
      updateTime()
      timer = setInterval(updateTime, 1000)

  // 更新等待时间
  waitTimeTimer = setInterval(updateWaitTime, 60000) // 每分钟更新一次

  // 加载用户信息
  loadUserInfo()

  // 初始化人脸验证页面
  initFaceVerifyPage()

  // 启动验证结果监听
  const cleanupVerifyCheck = checkFaceVerifyResult()

  // 保存清理函数以便在卸载时调用
  onBeforeUnmount(() => {
    cleanupVerifyCheck()
  })
})

onBeforeUnmount(() => {
  // 清除定时器
  if (timer) clearInterval(timer)
  if (waitTimeTimer) clearInterval(waitTimeTimer)

  // 停止验证窗口检查
  stopVerifyWindowCheck()

  // 关闭验证窗口（如果存在）
  if (faceVerifyWindow && !faceVerifyWindow.closed) {
    faceVerifyWindow.close()
  }

  // 清除重播定时器
  clearTimeout(callRepeatTimer.value)

  // 关闭广播通道
  const callWindowChannel = new BroadcastChannel('call_screen_channel')
  callWindowChannel.close()

  const callHistoryChannel = new BroadcastChannel('call_history_channel')
  callHistoryChannel.close()
})
</script>

<style scoped>
.call-terminal-container {
  height: 100vh;
  background-color: #f0f2f5;
}

.aside {
  background-color: #1976d2;
  color: white;
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.logo {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.logo-container h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.window-info {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.window-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.staff-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.staff-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.staff-name {
  font-size: 16px;
}

.waiting-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.waiting-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.waiting-title {
  font-size: 16px;
  font-weight: bold;
}

.waiting-count {
  font-size: 14px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
}

.waiting-item {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}

.waiting-item-first {
  background-color: rgba(255, 193, 7, 0.2);
}

.ticket-number {
  font-size: 20px;
  font-weight: bold;
  margin-right: 15px;
  min-width: 60px;
}

.ticket-info {
  flex: 1;
}

.business-type {
  font-size: 14px;
  margin-bottom: 5px;
}

.wait-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.statistics {
  display: flex;
  justify-content: space-around;
  padding: 20px;
}

.statistics-item {
  text-align: center;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
}

.statistics-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.main-container {
  flex-direction: column;
  height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  height: 60px;
  padding: 0 20px;
}

.current-time {
  font-size: 16px;
  color: #333;
}

.user-menu {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.user-menu span {
  margin: 0 5px;
}

.main {
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.service-area {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  height: 300px;
  display: flex;
  flex-direction: column;
}

.current-ticket {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.ticket-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.ticket-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.ticket-time {
  font-size: 14px;
  color: #666;
}

.ticket-content {
  display: flex;
  flex: 1;
  margin-bottom: 20px;
}

.ticket-big-number {
  font-size: 80px;
  font-weight: bold;
  color: #f44336;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200px;
}

.ticket-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.action-buttons {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.button-group:first-child {
  flex: 0.8;
}

.button-group:last-child {
  flex: 2;
  justify-content: space-between;
}

.button-group {
  display: flex;
  gap: 10px;
}

.action-button {
  flex: 1;
  min-width: 0; /* 允许按钮缩小 */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px; /* 减小高度 */
  font-size: 14px; /* 减小字体 */
  border-radius: 6px;
  transition: all 0.2s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 12px;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(0,0,0,0.08);
}

.replay-button {
  background-color: #409EFF;
}

.complete-button {
  background-color: #67C23A;
}

.noshow-button {
  background-color: #E6A23C;
}

.replay-button:hover {
  background-color: #66b1ff;
}

.complete-button:hover {
  background-color: #85ce61;
}

.noshow-button:hover {
  background-color: #ebb563;
}

.no-ticket {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.next-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.history-area {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.history-header {
  margin-bottom: 20px;
}

.history-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.staff-avatar-small {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.service-timer {
  font-size: 14px;
  color: #666;
}

.active {
  font-weight: bold;
  color: #f44336;
}

.no-ticket-button {
  margin-top: 10px;
  min-width: 120px;
  transition: all 0.2s ease;
  border-radius: 6px;
}

.no-ticket-button:hover:not([disabled]) {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(0,0,0,0.08);
}

@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }

  .button-group {
    width: 100%;
    gap: 8px;
  }

  .action-button {
    font-size: 13px;
    height: 36px;
  }
}
</style>
